package com.dragon.framework.decorator;

import com.dragon.common.constant.BasicConstant;
import com.dragon.common.utils.MdcUtils;
import org.springframework.core.task.TaskDecorator;
import org.springframework.lang.NonNull;

import java.util.Map;
import java.util.Objects;

/**
 * Mdc线程装饰器
 * 解决 当开启异步方法的时候，子线程获取不到主线程的TRACE_ID
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/16 16:06
 */
public class MdcTaskDecorator implements TaskDecorator {

    @NonNull
    @Override
    public Runnable decorate(@NonNull Runnable runnable) {
        Map<String, String> contextMap = MdcUtils.getCopyOfContextMap();

        return () -> {
            try {
                if (Objects.nonNull(contextMap)) {
                    MdcUtils.setContextMap(contextMap);
                    MdcUtils.put(BasicConstant.TRACE_ID, MdcUtils.safeGenerate(BasicConstant.TRACE_ID));
                }

                runnable.run();
            } finally {
                MdcUtils.remove(BasicConstant.TRACE_ID);
            }
        };
    }

}
